package com.nenglai.common.crud;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.nenglai.common.response.ErrorCode;
import com.nenglai.common.response.ResponseException;
import com.nenglai.common.util.SpringUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Data
@ToString
@NoArgsConstructor
public class RemoveBody {

    @JsonIgnore
    private static UpdateUtil updateUtil;
    @JsonIgnore
    private static SearchUtil searchUtil;
    /**
     * 查询条件
     */
    private List<JSONObject> conditions;
    /**
     * 数据
     */
    private Map<String, Object> data = new HashMap<>();
    /**
     * 实体类型字典
     */
    @JsonIgnore
    private Map<String, Class<?>> parallel;
    /**
     * 统计有效条件数量
     */
    @JsonIgnore
    private int conditionTotal = 0;

    static {
        updateUtil = SpringUtil.getBean(UpdateUtil.class);
        searchUtil = SpringUtil.getBean(SearchUtil.class);
    }

    /**
     * 获取data value
     *
     * @param key
     * @param clazz
     * @return T
     * @author kongdehui
     * @date 2021/04/22 13:58
     */
    public <T> T getDataValue(String key, Class<T> clazz) {
        Object obj = data.get(key);
        return TypeUtils.castToJavaBean(obj, clazz);
    }

    /**
     * @param updateWrapper
     * @param clazz
     * @param safe
     * @return com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<T>
     * @author kongdehui
     * @date 2021/04/22 20:04
     */
    public <T> UpdateWrapper<T> query(UpdateWrapper<T> updateWrapper, Class<?> clazz, boolean safe) {
        this.init(clazz);
        this.where(updateWrapper);
        if (safe && this.conditionTotal == 0) {
            throw new ResponseException(ErrorCode.FORBID_NO_CONDITION_REMOVE);
        }
        return updateWrapper;
    }

    /**
     * @param queryWrapper
     * @param clazz
     * @param safe
     * @return com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<T>
     * @author kongdehui
     * @date 2021/04/22 21:33
     */
    public <T> QueryWrapper<T> query(QueryWrapper<T> queryWrapper, Class<?> clazz, boolean safe) {
        this.init(clazz);
        this.where(queryWrapper);
        if (safe && this.conditionTotal == 0) {
            throw new ResponseException(ErrorCode.FORBID_NO_CONDITION_REMOVE);
        }
        return queryWrapper;
    }

    /**
     * 初始化（实体类型字典）
     *
     * @param clazz
     * @return void
     * @author kongdehui
     * @date 2021/04/21 18:45
     */
    private void init(Class<?> clazz) {
        Map<String, Class<?>> parallel = new HashMap<>();
        Field[] fields = clazz.getDeclaredFields();
        Field field;
        for (Field value : fields) {
            try {
                field = value;
                field.setAccessible(true); // 开启访问权限
                parallel.put(field.getName(), field.getType());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.parallel = parallel;
    }

    /**
     * 条件查询
     *
     * @param query
     * @return void
     * @author kongdehui
     * @date 2021/04/22 20:04
     */
    public void where(UpdateWrapper<?> query) {
        if (conditions != null) {
            Iterator<JSONObject> iterator = conditions.iterator();
            while (iterator.hasNext()) {
                JSONObject next = iterator.next();
                if (updateUtil.condition(query, next, parallel))
                    this.conditionTotal++;
            }
        }
    }

    /**
     * @param query
     * @return void
     * @author kongdehui
     * @date 2021/04/22 21:32
     */
    public void where(QueryWrapper<?> query) {
        if (conditions != null) {
            Iterator<JSONObject> iterator = conditions.iterator();
            while (iterator.hasNext()) {
                JSONObject next = iterator.next();
                if (searchUtil.condition(query, next, parallel))
                    this.conditionTotal++;
            }
        }
    }
}

